/**   
 * @Title: SecurityUtil.java 
 * @Package cn.edu.cdtu.healthserver.utils 
 * @Description: TODO 
 * @author  
 * @date 
 * @version V0.0   
 */
package cn.edu.cdtu.healthserver.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/** 
 * @ClassName: SecurityUtil 
 * @Description: TODO
 * @author 
 * @date 
 *  
 */
public class SecurityUtil {

	//加密中添加的固定保密字串
	private static final String KEY = ":health@team01.scu.edu.cn";
	//16进制数字典
	private static final char HEX_DIGITS[] =
		{'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
	
	/**
	 * 
	 * @Title: calculateMD5 
	 * @Description: 计算MD5并转换为字符串表示
	 * @return String
	 * @throws 
	 *
	 * @param source
	 * @return
	 */
	public static final String  calculateMD5(String source){
		if(source == null || "".equals(source))
			return null;
		try {
			byte[] stringData = source.getBytes();
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			md5.update(stringData);
			byte[] newData = md5.digest();
			int dataLength = newData.length;
			char newString[] = new char[dataLength * 2];
			for(int i=0,k=0;i<dataLength;i++){
				byte temp = newData[i];
				newString[k++] = HEX_DIGITS[temp >>> 4 & 0xF];
				newString[k++] = HEX_DIGITS[temp & 0xF];
			}
			return new String(newString);
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 
	 * @Title: encryptPassword 
	 * @Description: 加密密码
	 * @return String
	 * @throws 
	 *
	 * @param password
	 * @return
	 */
	public static final String encryptPassword(String password){
		String source = KEY + password;
		return calculateMD5(source);
	}
}
